package com.hb.config.web;

import com.hb.util.ContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * spring拦截器
 * 这个拦截器在shiro的过滤器之后执行
 *
 * @author zhaojk
 */
@Slf4j
@Component
public class HbplatInterceptor implements HandlerInterceptor {

    /**
     * 方法前置处理
     *
     * @param request
     * @param response
     * @param handler
     *
     * @return
     *
     * @throws Exception
     */
    @Override
    public boolean preHandle(
            HttpServletRequest request, HttpServletResponse response,
            Object handler) throws Exception {
        // 处理跨域
        String origin = request.getHeader("Origin");
        handler(response, origin);

        log.info("拦截器执行, 在方法之前");
//        if ("OPTIONS".equals(request.getMethod())) {
//            return true;
//        }

//        String apiPath = request.getRequestURI(); // 请求的接口
//        log.info(apiPath);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler,
                           @Nullable ModelAndView modelAndView) throws Exception {
        log.info("拦截器执行, 方法后执行");
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler,
                                @Nullable Exception ex) throws Exception {
        log.info("拦截器执行, 请求处理完成执行");
    }

    private void handler(HttpServletResponse response, String origin) {
        ContextUtil.preHandle(response, origin);
    }
}